package com.flqy.baselibrary.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import androidx.annotation.NonNull;

public class OpenAppUtils {

    private final static String PDD_PKG_NAME = "com.xunmeng.pinduoduo";
    private final static String TAOBAO_PKG_NAME = "com.taobao.taobao";
    private final static String TMALL_PKG_NAME = "com.tmall.wireless";
    private final static String WECHAT_PKG_NAME = "com.tencent.mm";

    public static boolean isPDDInstall(Context context) {
        return checkHasInstalledApp(context, PDD_PKG_NAME);
    }

    public static boolean isTaoBaoInstall(Context context) {
        return checkHasInstalledApp(context, TAOBAO_PKG_NAME);
    }

    public static boolean isTMallInstall(Context context) {
        return checkHasInstalledApp(context, TMALL_PKG_NAME);
    }

    public static boolean isWechatInstall(Context context) {
        return checkHasInstalledApp(context, WECHAT_PKG_NAME);
    }

    public static void openTaoBao(Context context) {
        openApk(context, TAOBAO_PKG_NAME);
    }

    public static void openPDD(Context context) {
        openApk(context, PDD_PKG_NAME);
    }

    public static void openTmall(Context context) {
        openApk(context, TMALL_PKG_NAME);
    }

    public static void openWechat(Context context) {
        openApk(context, WECHAT_PKG_NAME);
    }

    /**
     * 启动第三方apk
     * 直接打开  每次都会启动到启动界面，每次都会干掉之前的，从新启动
     * XXXXX ： 包名
     */
    public static void openApk(Context context, String pkgName) {
        PackageManager packageManager = context.getPackageManager();
        Intent it = packageManager.getLaunchIntentForPackage(pkgName);
        if(it!=null) {
            context.startActivity(it);
        }
    }

    public static boolean checkHasInstalledApp(@NonNull Context context, String pkgName) {
        PackageManager pm = context.getPackageManager();
        boolean app_installed;
        try {
            pm.getPackageInfo(pkgName, PackageManager.GET_GIDS);
            app_installed = true;
        } catch (PackageManager.NameNotFoundException e) {
            app_installed = false;
        } catch (RuntimeException e) {
            app_installed = false;
        }
        return app_installed;
    }
}
